<?php

namespace app\api\controller\order;

use app\api\controller\Api;
use app\common\audit\logic\AuditResultLogic;
use app\common\order\model\Order;
use app\common\order\model\OrderProduct;
use app\common\order\model\OrderProtocol;
use app\common\order\validate\OrderProtocolValidate;
use app\common\system\model\OperateLog;
use think\db\exception\DbException;
use think\Exception;

class Protocol extends Api
{
    public function create()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        //
        $where = [];
        $where[] = ['order_id', '=', $post['order_id']];
        $where[] = ['type', '=', '0'];
        // StoreCategory
        $hasWhere = [];
        $hasWhere[] = ['order_model', 'in', ['Banquet', 'Meeting', 'Baby']];
        $masterProduct = OrderProduct::hasWhere('StoreCategory', $hasWhere)->where($where)->find();
        if (empty($masterProduct)) return error([], "数据异常");

        $post['company_id'] = $masterProduct['company_id'];
        $post['category_id'] = $masterProduct['category_id'];
        // 验证收款信息
        $validate = new OrderProtocolValidate();
        if (!$validate->check($post)) {
            return error([], $validate->getError());
        }

        $source = [];
        // 收款信息
        $post['user_id'] = $user['id'];
        $model = new OrderProtocol();
        $model->startTrans();

        $modelName = OrderProtocol::class;
        try {
            $model->save($post);
            $source[$modelName] = $model->id;
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $orderModel = new Order();
        $order = $orderModel->where('id', $post['order_id'])->find();

        $auditRsLogic = new AuditResultLogic();
        $master = $order->getData();
        $options = [
            'company_id' => $post['company_id'],
            'timing' => 'protocol'
        ];
        try {
            $auditNo = $auditRsLogic->initAudit($master, $user, $source, $options);
            foreach ($source as $className=>$row) {
                try {
                    $where = [];
                    if (is_array($row)) {
                        $where[] = ['id', 'in', $row];
                    } else {
                        $where[] = ['id', '=', $row];
                    }
                    $class = new $className;
                    $class->where($where)->save(['check_no' => $auditNo]);
                } catch (DbException $e) {
                    return error([], $e->getMessage());
                }
            }
            $model->commit();

            return success([], '操作成功');
        } catch (Exception $e) {
            $msg = $e->getMessage();
        } catch (DbException $e) {
            $msg = $e->getMessage();
        }
        return error([], $msg, 404);
    }

    public function save()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        //
        $where = [];
        $where[] = ['order_id', '=', $post['order_id']];
        $where[] = ['type', '=', '0'];
        // StoreCategory
        $hasWhere = [];
        $hasWhere[] = ['order_model', 'in', ['Banquet', 'Meeting', 'Baby']];
        $masterProduct = OrderProduct::hasWhere('StoreCategory', $hasWhere)->where($where)->find();
        if (empty($masterProduct)) return error([], "数据异常");

        $post['company_id'] = $masterProduct['company_id'];
        $post['category_id'] = $masterProduct['category_id'];
        // 验证收款信息
        $validate = new OrderProtocolValidate();
        if (!$validate->check($post)) {
            return error([], $validate->getError());
        }

        $source = [];
        // 收款信息
        $post['user_id'] = $user['id'];
        $model = new OrderProtocol();
        $model->startTrans();

        $modelName = OrderProtocol::class;
        try {
            $protocol = $model->where('id', $post['id'])->find();
            $protocol->save($post);
            $source[$modelName] = $post['id'];
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $orderModel = new Order();
        $order = $orderModel->where('id', $post['order_id'])->find();

        $auditRsLogic = new AuditResultLogic();
        $master = $order->getData();
        $options = [
            'company_id' => $post['company_id'],
            'timing' => 'protocol'
        ];
        try {
            $auditNo = $auditRsLogic->initAudit($master, $user, $source, $options);
            foreach ($source as $className=>$row) {
                try {
                    $where = [];
                    if (is_array($row)) {
                        $where[] = ['id', 'in', $row];
                    } else {
                        $where[] = ['id', '=', $row];
                    }
                    $class = new $className;
                    $class->where($where)->save(['check_no' => $auditNo]);
                } catch (DbException $e) {
                    return error([], $e->getMessage());
                }
            }
            $model->commit();

            return success([], '操作成功');
        } catch (Exception $e) {
            $msg = $e->getMessage();
        } catch (DbException $e) {
            $msg = $e->getMessage();
        }
        return error([], $msg, 404);
    }

    public function update()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        // 验证提交
        $validate = new OrderProtocolValidate();
        if (!$validate->check($post)) return error([], $validate->getError());

        $model = new OrderProtocol();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '数据已不存在');

        $model->startTrans();
        try {
            $post['user_id'] = $user['id'];
            $origin = $row->getData();
            $row->save($post);

            $changed = $row->getData();
            $modelName = OrderProtocol::class;
            OperateLog::write($user['id'], $post['order_id'], $origin, $changed, $modelName);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }
        $model->commit();

        return success([], '更新成功');
    }
}